/**@description 获取当前环境
 * @return string
 * */
const getEnv = () => {
    const hostname = window.location.hostname;
    if (hostname.includes("localhost")) {
        return "develop";
    }
    if (hostname.includes("ntzq.tech")) {
        return "test";
    }
    if (hostname.includes("goupapp.com")) {
        return "production";
    }
    return "develop";
}

/**@description md5加密
 * */
const encryption = (sign) => {
    const md5 = new Md5();
    return md5.appendStr(sign).end();
}

const getRequsetPath = () => {
    const env = getEnv();
    return env === "production" ? "https://api.goupapp.com" : "https://api.ntzq.tech";
}

const getStaticUrl = () => {
    const env = getEnv();
    return env === "production" ? "https://static.goupapp.com/" : "https://static.ntzq.tech/";
}

let header= {
    platform: "web",
    appId: 10001,
    key: "keyzQPl@yQghq&)hfw*$&UHI_",
    appSign: "",
    appLang: "",
    timestamp: 0,
    access_token: "",
    user_id: 0
};

function getUa(){
    if(navigator.userAgent.indexOf("electron") === -1){
        return "web";
    }else{
        return "pc";
    }
}

const getDataToJson = (data) => {
    if (data.data && typeof data.data === 'object' && !Array.isArray(data.data)) {
        const sortedKeys = Object.keys(data.data).sort((a, b) => a.localeCompare(b));
        const keyValuePairs = sortedKeys.map(key => `${key}=${data.data[key]}`);
        if (keyValuePairs.length === 0) {
            return "";
        }
        return keyValuePairs.join('&');
    } else {
        return "";
    }
}

const setHeader = (data) => {
    data.headers = data.headers || {}; //防止headers不存在
    data.data = data.data || {}; //防止data不存在
    const timestamp = new Date().getTime();
    data.data.appid = header.appId;
    data.data.timestamp = timestamp;
    const setAppSign = (data) => {
        const data_json = getDataToJson(data);
        const sign = data_json + header.key;
        return encryption(sign);
    };
    const userStore = useUserStore();
    const {user_state} = storeToRefs(userStore);
    header.timestamp = timestamp; // 时间戳
    header.appSign = setAppSign(data); //设置签名
    data.headers["App-Platform"] = getUa();
    data.headers["Timestamp"] = header.timestamp;
    data.headers["AppSign"] = header.appSign;
    data.headers["App-Lang"] = header.appLang;
    data.headers["Access-Token"] = user_state.value.access_token;
    data.headers["User-Id"] = user_state.value.user_id;
    data.data["appSign"] = header.appSign;
    return data;
}